package com.citybrain.rnapp.modules;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.RequiresApi;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
// import com.getui.reactnativegetui.GetuiModule;
import com.hengqin.macao.activity.WebActivity;

public class ReactNativeReLoadModule extends ReactContextBaseJavaModule {

    private static final String REACT_APPLICATION_CLASS_NAME = "com.facebook.react.ReactApplication";

    private static final String REACT_NATIVE_HOST_CLASS_NAME = "com.facebook.react.ReactNativeHost";

    private LifecycleEventListener mLifecycleEventListener = null;

    ReactInstanceManager instanceManager = null;

    public ReactNativeReLoadModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    private void loadBundleLegacy() {
        final Activity currentActivity = getCurrentActivity();
        if (currentActivity == null) {
            // The currentActivity can be null if it is backgrounded / destroyed, so we simply
            // no-op to prevent any null pointer exceptions.
            return;
        }

        currentActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.recreate();
            }
        });
    }

    private void loadBundle() {
        clearLifecycleEventListener();
        try {
            final ReactInstanceManager instanceManager = resolveInstanceManager();
            if (instanceManager == null) {
                return;
            }

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    try {
                        instanceManager.recreateReactContextInBackground();
                    }
                    catch (Exception e) {
                        loadBundleLegacy();
                    }
                }
            });

        }
        catch (Exception e) {
            loadBundleLegacy();
        }
    }

    private ReactInstanceManager resolveInstanceManager() throws NoSuchFieldException, IllegalAccessException {

        final Activity currentActivity = getCurrentActivity();
        if (currentActivity == null) {
            return null;
        }

        ReactApplication reactApplication = (ReactApplication) currentActivity.getApplication();
        instanceManager = reactApplication.getReactNativeHost().getReactInstanceManager();

        return instanceManager;
    }

    private void clearLifecycleEventListener() {
        // Remove LifecycleEventListener to prevent infinite restart loop
        if (mLifecycleEventListener != null) {
            getReactApplicationContext().removeLifecycleEventListener(mLifecycleEventListener);
            mLifecycleEventListener = null;
        }
    }

    @ReactMethod
    public void reload() {
        loadBundle();
    }

    @ReactMethod
    public void toWebViewActivity(String url,String host,String name,String closeTxt) {

        Intent intent = new Intent(getCurrentActivity(), WebActivity.class);
        intent.putExtra("URL",url);
        intent.putExtra("HOST",host);
        intent.putExtra("Name",name);
        intent.putExtra("CloseTxt",closeTxt);
        getCurrentActivity().startActivity(intent);
    }

    @ReactMethod
    public void openBrowser(String url)
    {
        openBrowser(getCurrentActivity(), url);
    }


        /**
         * 调用第三方浏览器打开
         *
         * @param context
         * @param url 要浏览的资源地址
         */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            //            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            // 打印Log
            // ComponentName到底是什么
            // L.d("componentName
            // = " +
            // componentName.getClassName());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        }

    }

    /**
     * 判断Android系统版本是否 >= LOLLIPOP(API21)
     *
     * @return boolean
     */
    private boolean isLOLLIPOP() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 初始化
     */
    @ReactMethod
    public void initPush(){
        // GetuiModule.initPush(getCurrentActivity());
    }

    /**
     * 关闭启动屏
     */
    @ReactMethod
    public void exitApp() {
        if (getCurrentActivity() != null)
            getCurrentActivity().finish();
        System.exit(0);
    }

    @Override
    public String getName() {
        return "RNReload";
    }

}